<template>
  <el-dropdown @command="handleLanguageChange" size="medium">
    <span class="el-dropdown-link">
      {{ currentLanguageName }}
      <el-icon><arrow-down /></el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item 
          v-for="(lang, key) in languages" 
          :key="key" 
          :command="key"
          :disabled="currentLanguage === key"
        >
          {{ lang.name }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ArrowDown } from '@element-plus/icons-vue'
import languageUtil from '@/utils/language'

export default {
  name: 'LanguageSelector',
  components: {
    ArrowDown
  },
  setup() {
    const { locale } = useI18n()
    
    const currentLanguage = ref(languageUtil.getCurrentLanguage())
    const languages = {
      en: { name: 'English' },
      zh: { name: '中文' }
    }
    
    const currentLanguageName = computed(() => {
      return languages[currentLanguage.value]?.name || 'Language'
    })

    const handleLanguageChange = (selectedLang) => {
      if (selectedLang !== currentLanguage.value) {
        currentLanguage.value = selectedLang
        locale.value = selectedLang
        languageUtil.setLanguage(selectedLang)
      }
    }

    onMounted(() => {
      // Set the initial language based on user preference or browser settings
      const initialLang = languageUtil.getCurrentLanguage()
      locale.value = initialLang
      currentLanguage.value = initialLang
    })

    return {
      currentLanguage,
      currentLanguageName,
      languages,
      handleLanguageChange
    }
  }
}
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  display: flex;
  align-items: center;
}
</style>